package cs.sy.service.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cs.sy.service.bean.UserBean;
import cs.sy.service.business.UserLoginBuss;

public class RegisterServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			String name = URLDecoder.decode(req.getParameter("name"), "UTF-8");
			String pass = req.getParameter("pass");
			int sex = Integer.parseInt(req.getParameter("sex"));
			UserBean userBean = new UserBean();
			userBean.setName(name);
			userBean.setPass(pass);
			userBean.setSex(sex);
			boolean result = new UserLoginBuss().insertUser(userBean);
			if(result){
				req.setAttribute("result", "注册成功...");
				req.getSession().setAttribute("user", userBean);
				req.setAttribute("food",new UserLoginBuss().getAllFood());
				req.getRequestDispatcher("/food.jsp").forward(req, resp);
			}else{
				req.setAttribute("result", "注册失败...");
				req.getRequestDispatcher("/index.jsp").forward(req, resp);
			}
		}catch (Exception e) {
			req.setAttribute("result", "内部错误,注册失败...");
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		}
	}
}
